﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;
using System.Windows.Forms;

using DEFUSE;
using System.Data;

namespace auxiliary_proj
{
    static class Employee
    {
        private static string _name = "Guest", fName = "", lName = "", _email = "", _username = "", _password = "";
        private static int _permission = 0;
        private static string _phone = "";
        private static Bitmap _pic;

        //server connection stuff
        private static MySqlCommand command;
        private static MySqlConnection connection;


        public static string formatPhone(string _phone)
        {
            return String.Format("{0: (###) ###-####}", _phone);

        }

        public static void verifyUser(string name, string password) { }

        public static void iCreateUser()
        {
            new FormCreateUser();
        }

        public static void resetUser()
        {
            _name = "Guest";
            _email = "";
            _username = "";
            _permission = 0; //no access besides login
            _phone = "";
            _pic = null; //silhouette default user img
        }
        //do login query
        public static void login(string name, string pass)
        {
            connection = new MySqlConnection(Program.getConnection());

            string query = "SELECT u.user_name AS User, u.password AS Password, u.access_lvl AS Access, u.first_name, u.last_name, u.email, u.photo " +
                        "FROM USER AS u WHERE u.user_name = \"" + name + "\"";
            command = new MySqlCommand(query, connection);
            Home home = Singleton.getHome();
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                connection.Open();
                try
                {
                    MySqlDataReader values = command.ExecuteReader();

                    Object[] value;
                    if (values.Read()) //if expecting multiple results use while() and then add the Object[] to arraylist to parse multiple columns/lines
                    {
                        value = new Object[values.FieldCount];
                        values.GetValues(value);
                        name = value[0].ToString();
                        //hashed password, and store that hash (for use in update user info)
                        string password = value[1].ToString();
                        Employee.Password = value[1].ToString();


                        //compare typed password to hashed password
                        if (PasswordHash.ValidatePassword(pass, password))//pass.Equals(password))
                        {
                            //if login is successful set access lvl to what was returned for the user
                            Employee.Permission = int.Parse(value[2].ToString());
                            Employee.Name = value[3].ToString() + " " + value[4].ToString();
                            Employee.fName = value[3].ToString();
                            Employee.lName = value[4].ToString();
                            Employee.Email = value[5].ToString();
                            Employee.User = name;
                            Employee.Picture = (Bitmap)Image.FromStream(new System.IO.MemoryStream((byte[])value[6]));

                            //set the values from user login to welcome panel
                            home.lblWelcome.Text = "Welcome, " + Employee.fName + " " + Employee.lName + "!";
                            home.lbfName.Text = Employee.fName;
                            home.lbLastName.Text = Employee.LastName;
                            home.lblEmail.Text = Employee.Email;
                            if (Employee.Permission == 2)
                            {
                                home.lblAccess.Text = "Admin";
                                Singleton.getMainForm().qNewPendingSalesOrderCount();
                            }
                            else if (Employee.Permission == 1)
                            {
                                home.lblAccess.Text = "User";
                                Singleton.getMainForm().qNewActiveSalesOrderCount();
                            }

                            //timers
                            MainForm mf = Singleton.getMainForm();
                            mf.orderStatus_timer.Start();
                            mf.idle_timer.Interval = mf.idleTime * 1000;
                            mf.idle_timer.Start();


                            //do initial queries to fill Hashtables
                            Query.populateHashtable("CATID_DESC", "");
                            Query.populateHashtable("ITEMID_DESC", "");
                            Query.populateHashtable("VENDORCODE_DESC", "");

                            home.picUser.Image = Employee.Picture;
                            mf.qInventory();
                            mf.setFunctionality();
                            home.qNewMsgCount();
                            DataTable res = Query.select("SELECT * FROM purchase_order where status = '0' order by timestamp ASC");
                            Singleton.getMainForm().MainPODataGridView.DataSource = res;
                        }
                        else
                        {
                            MessageBox.Show("Login failed!\nUser," + name + ", has invalid password!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("User does not Exist!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (MySqlException exc) { MessageBox.Show(exc.Message); }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }
            Cursor.Current = Cursors.Default;
        }

        public static void logout()
        {
            //clear currently logged in user, and then show login again on the Home Control in Main Form
            //Singleton.getMainForm().orderStatus_timer.Enabled = false;
            Singleton.disposeObjects();
            resetUser();

            //close all forms except main form

            MainForm mf = Singleton.getMainForm();
            List<Form> open = new List<Form>();

            /*
             * runtime did not like closing and disposing from Application.OpenForms
             * so had to add each form to a List and then close and dispose those
             */
            foreach (Form f in Application.OpenForms)
            {
                if (!(f is MainForm))
                {
                    open.Add(f);
                }
            }

            foreach (Form f in open)
            {
                f.Close();
                f.Dispose();
            }


            Home h = Singleton.getHome();
            h.tbUserName.Text = "";
            h.tbPassword.Text = "";
            mf.pnlMain.Controls.Clear();
            mf.setFunctionality();
            mf.pnlMain.Controls.Add(Singleton.getHome());
            mf.lbSalesOrder.Hide();
            h.pLogin.Show();

            Singleton.getMainForm().idle_timer.Stop();
            Singleton.getMainForm().orderStatus_timer.Stop();
        }

        public static string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
        public static string FirstName
        {
            get
            {
                return fName;
            }
            set
            {
                fName = value;
            }
        }
        public static string LastName
        {
            get
            {
                return lName;
            }
            set
            {
                lName = value;
            }
        }

        public static string Email
        {
            get
            {
                return _email;
            }
            set
            {
                _email = value;
            }
        }

        public static string User
        {
            get
            {
                return _username;
            }
            set
            {
                _username = value;
            }
        }
        public static string Password
        {
            get
            {
                return _password;
            }
            set
            {
                _password = value;
            }
        }

        public static int Permission
        {
            get
            {
                return _permission;
            }
            set
            {
                _permission = value;
            }
        }

        public static string Phone
        {
            get
            {
                return _phone;
            }
            set
            {
                _phone = value;
            }
        }

        public static Bitmap Picture
        {
            get
            {
                return _pic;
            }
            set
            {
                _pic = value;
            }
        }
    }
}
